﻿#include "StdAfx.h"
#include "Effect.h"
#include "ParticleSystem.h"
#include "StringUtility.h"
#include "json.h"
#include <fstream>

CEffect::CEffect(void)
{
	m_fDuration = cocos2d::kCCParticleDurationInfinity;
	m_fEffectTime = 0.0f;
}

CEffect::~CEffect(void)
{
	cleanEffectUnit();
}
//------------------------------------------------------------------------------
/** creates an initializes a Effect from a plist file.
//This plist files can be created manually or with Particle Designer:
//http://particledesigner.71squared.com/
@since v2.0
*/
CEffect* CEffect::create(const char * szEffectFileName)
{
	CEffect *pRet = new CEffect();
	if (pRet && pRet->initWithFile(szEffectFileName))
	{
		pRet->autorelease();
		return pRet;
	}
	CC_SAFE_DELETE(pRet);

	return pRet;
}
//------------------------------------------------------------------------------
/**
*@brief 从文件创建特效
*@param szEffectFileName 文件名
*/
#define OUTPUT_LOG(format, ...) \
static char g_szBuff[1024]; \
sprintf_s( g_szBuff, 1024, format, ##__VA_ARGS__ ); \
OutputDebugStringA( g_szBuff );

bool CEffect::initWithFile( const char* szEffectFileName )
{
	// 先是从文件中构建Prop结构

	//然后通过Prop创建EffectUnit
	//if( szEffectFileName == NULL || szEffectFileName[0] == 0 )
	//{
	//	return false;
	//}

	//unsigned long lSize = 0;
	//unsigned char* buf = cocos2d::CCFileUtils::sharedFileUtils()->getFileData( szEffectFileName, "rt", &lSize );
	//char* pBuff = new char[lSize + 3];

	//memcpy( pBuff, buf, lSize );

	//pBuff[lSize] = '\r';
	//pBuff[lSize+1] = '\n';
	//pBuff[lSize+2] = 0;

	///// 将文件按行读出
	//BYTE* pContent = (BYTE*)pBuff;
	//if( pContent[0] == 0xef && pContent[1] == 0xbb && pContent[2] == 0xbf ) /// 则认为文件是utf8编码
	//{
	//	pBuff += 3;
	//}

	//std::vector<std::string> strList;
	//char* finder = strstr((char*)pBuff,"\r\n");
	//char* oldfinder = (char*)pBuff;
	//while(finder!=NULL)
	//{
	//	std::string str;
	//	str.append(oldfinder,finder);
	//	strList.push_back(str);
	//	oldfinder = finder + 2;
	//	finder=strstr(oldfinder,"\r\n");
	//}

	//for (int i=0;i<(int)strList.size();i++)
	//{
	//	if(strList[i].empty())		/// 空行直接不处理
	//	{
	//		continue;
	//	}

	//	/// 不支持行内注释
	//	if(strList[i].find("//",0) == 0 || strList[i].find("#",0) == 0 ) /// 忽略掉注释
	//	{			
	//		continue;
	//	}

	//	cocos2d::engine::StringUtility::trim(strList[i]);

	//	parseLine(strList[i]);
	//}

	//OUTPUT_LOG( "粒子系统周期:%f\n", 10.0f );

	////CParticleSystemProp* pParticleSysProp = new CParticleSystemProp();
	////if( pParticleSysProp )
	////{
	////	//cocos2d::CCLog( "粒子系统周期:%f\n", pParticleSysProp->getDuration() );
	////	//char szBuff[256];
	////	//sprintf_s( szBuff, 256, "粒子系统周期:%f\n", pParticleSysProp->getDuration() );
	////	//OutputDebugStringA( szBuff );
	////	//sprintf_s( szBuff, 256, "粒子系统点大小:%f\n", pParticleSysProp->getPointSize() );
	////	//OutputDebugStringA( szBuff );
	////}

	////delete pParticleSysProp;

	///// 测试代码
	//SEffectTrack sEffectTrack;
	//sEffectTrack.fStarPos = 0.0f;
	//sEffectTrack.fEndPos = 10.0f;
	//CParticleSystem* pParticleSys = new CParticleSystem();
	//if( pParticleSys )
	//{
	//	pParticleSys->create(NULL);
	//}
	//sEffectTrack.pEffectUnit = pParticleSys;
	//sEffectTrack.ptOffset.x = 30;
	//sEffectTrack.ptOffset.y = 50;

	//m_mapEffect.insert( std::make_pair( 0, sEffectTrack ) );

	//sEffectTrack;
	//sEffectTrack.fStarPos = 3.0f;
	//sEffectTrack.fEndPos = 8.0f;
	//pParticleSys = new CParticleSystem();
	//if( pParticleSys )
	//{
	//	pParticleSys->create(NULL);
	//}
	//sEffectTrack.pEffectUnit = pParticleSys;
	//sEffectTrack.ptOffset.x = -30;
	//sEffectTrack.ptOffset.y = -50;

	//m_mapEffect.insert( std::make_pair( 1, sEffectTrack ) );

	//m_fDuration = cocos2d::kCCParticleDurationInfinity;

	///// 播放中的轨道列表
	//m_setTracks.clear();

	//this->scheduleUpdate();

	return true;
}
//------------------------------------------------------------------------------
/**
*@brief 刷新
*@param 
*/
void CEffect::update( float dt )
{
	m_fEffectTime += dt;

	
	bool bInfinity = false;
	if( m_fDuration == cocos2d::kCCParticleDurationInfinity )
	{
		bInfinity = true;
	}

	EffectMap::iterator iter = m_mapEffect.begin();
	for( ; iter != m_mapEffect.end(); ++iter )
	{
		SEffectTrack& track = iter->second;
		if( m_fEffectTime < track.fStarPos )
		{
			continue;
		}
		else if( m_fEffectTime >= track.fStarPos && m_fEffectTime <= track.fEndPos )
		{
			if( m_setTracks.find( iter->first ) == m_setTracks.end() )
			{
				if( track.pEffectUnit )
				{
					track.pEffectUnit->attach( this );
					track.pEffectUnit->setOffset( track.ptOffset );
					m_setTracks.insert( iter->first );
				}
			}
		}
		else
		{
			if( track.pEffectUnit && m_setTracks.find( iter->first ) != m_setTracks.end() && !bInfinity )
			{
				track.pEffectUnit->detach();
				m_setTracks.erase( iter->first );
			}
		}
	}

	if( m_fDuration != cocos2d::kCCParticleDurationInfinity && m_fEffectTime >= m_fDuration )
	{
		m_fEffectTime = 0.0f;
	}
}
//------------------------------------------------------------------------------
/**
*@brief	保存特效设置到文件(json格式) 
*@param szEffectFileName 特效文件名
*/
void CEffect::save( const char* szEffectFileName )
{
	//Json::Value root;
	//root.append();

	//root.in

    //Json::Reader reader;  
    //bool ok = reader.parse(infile,root); //直接传入一个ifstream就可以了，全部解析到root中，当然文件可别太大。。对我来说这种DOM的方式是很适合的  
    //if(!ok)  
    //{  
    //    return false;  
    //}  
    //std::string name = root.get("str test","").asString(); //测试读入属性值  
    //std::cout<<name<<std::endl;  
    ////测试写入属性值，可直接生成新的键值对，以及对象，其实我之前的test.json是个空的，都是在这儿写入的  
    //root["interger test"] = 1;  
    //root["float test"] = 1.0f;  
    //root["obj"]["a"] = "obja";  
    //root["obj"]["b"] = "objb";  
    //root["obj"]["c"] = 0.13f; 

	//Json::Value root;

	//EffectMap::iterator iter = m_mapEffect.begin();
	//int nIndex = 0;
	//for( ; iter != m_mapEffect.end(); ++iter )
	//{
	//	Json::Value track;
	//	track["index"] = nIndex;
	//	track["startpos"] = iter->second.fStarPos;
	//	track["endpos"] = iter->second.fEndPos;
	//	track["offset_x"] = iter->second.ptOffset.x;
	//	track["offset_y"] = iter->second.ptOffset.y;
	//	root.append(track);
	//}

	//Json::StyledWriter writer;  
 //   std::string output = writer.write(root);  
	////std::cout<<output;

 //   //直接写入文件，搞定  
	//std::ofstream file;
	//file.open(szEffectFileName);  
	//file<<output;
	//file.close();
}
//------------------------------------------------------------------------------
/**
*@brief 清理特效单元
*@param 
*/
void CEffect::cleanEffectUnit()
{
	EffectMap::iterator iter = m_mapEffect.begin();
	for( ; iter != m_mapEffect.end(); ++iter )
	{
		SEffectTrack& track = iter->second;
		if( track.pEffectUnit )
		{
			delete track.pEffectUnit;
		}
	}

	m_mapEffect.clear();
}
//------------------------------------------------------------------------------
/**
*@brief 解析文件行
*@param strLine [in] 文本行
*/
void CEffect::parseLine( const std::string& strLine )
{
	static int nToken = 0;
	if( strLine == "effect" )
	{
	}
}